package com.wechat.service.quartz.config;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import java.util.List;

import org.quartz.CronScheduleBuilder;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import com.wechat.service.quartz.bo.InitJobBo;


/**
 * 初始化定时任务
 * 
 * @author admin
 *
 */
@Component
public class InitJob {
	private final static Logger log = LoggerFactory.getLogger(InitJob.class);
	public final static String TRIGGER = "Trigger";

	@Autowired(required = false)
	private Scheduler scheduler;

	/**
	 * 初始化定时任务
	 * 
	 * @param listInitJobBo
	 * @throws Exception
	 */
	public void init(@Validated List<? extends InitJobBo> listInitJobBo) throws Exception {

		if (scheduler == null) {
			log.error("Scheduler 未初始化！");
		} else {

			for (InitJobBo initJobBo : listInitJobBo) {

				if (!initJobBo.getTaskRun())
					continue;
				Job newInstance = (Job) Class.forName(initJobBo.getClassName()).newInstance();
				JobDetail job = newJob(newInstance.getClass())
						.withIdentity(initJobBo.getTaskName(), initJobBo.getTaskGroup()).build();

				Trigger trigger = newTrigger()
						.withIdentity(initJobBo.getTaskName() + TRIGGER, initJobBo.getTaskGroup() + TRIGGER).startNow()
						.withSchedule(CronScheduleBuilder.cronSchedule(initJobBo.getTaskCron())).build();

				scheduler.scheduleJob(job, trigger);

				scheduler.start();
			}
		}
	}
}
